﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public enum ID {ID_ARCHER,ID_SOLDIER,ID_CANNON,ID_GENERAL};
public delegate void OnSelectedTokenPiece(GameObject Token);

public class TokenPiece : MonoBehaviour 
{
	[HideInInspector]
	public int BoardPosition;
	public ID TokenID;
	public Texture2D	SoldierDefenseImage; // ONLY if this Token is a soldier
	private Texture 	_DefaultImage;
	[HideInInspector]
	public bool 		IsSoldierInDefenseMode; // ONLY if this Token is a soldier
	[HideInInspector]
	public bool			IsCannonReady;			// ONLY if this Token is a cannon

	private int _maxAttack;
	private int _maxMovement;

	[HideInInspector]
	public int _attack;
	[HideInInspector]
	public int _movement; // player must move before attacking, player cannot attack before moving

	[HideInInspector]
	public List<BoardPiece> _possibleMoves;

	[HideInInspector]
	public Vector3 StartPosition;

	public OnSelectedTokenPiece OnTokenSelected;
	public OnSelectedTokenPiece OnTokenAttacked;
	public OnSelectedTokenPiece OnAbilityTriggered;

	public ClickHandler ClickerHandler;

	void Start()
	{
		ClickerHandler.OnPressed += OnSelected;
		ClickerHandler.OnRPressed += OnAttacked;
		ClickerHandler.OnMPressed += OnTriggered;

		// temporary
		StartPosition = new Vector3 (transform.position.x,transform.position.y,transform.position.z);

		switch (TokenID) 
		{
		case ID.ID_ARCHER:
			_maxMovement = _maxAttack = 2;
			break;
		case ID.ID_CANNON:
			// movement and attacking is only applicable if 2 friendly pieces are adjacent to it
			_maxMovement = 0;
			_maxAttack = 0;
			break;
		case ID.ID_GENERAL:
			_maxMovement = 2;
			_maxAttack = 1;
			break;
		case ID.ID_SOLDIER:
			_maxMovement = _maxAttack = 1;
			break;
		}
		_attack = _maxAttack;
		_movement = _maxMovement;

		_DefaultImage = renderer.material.mainTexture;
	}

	public void Reset()
	{
		_attack = _maxAttack;
		_movement = _maxMovement;
	}

	public void RestartToPosition()
	{
		_attack = _maxAttack;
		_movement = _maxMovement;
		transform.position = new Vector3 (StartPosition.x,StartPosition.y,StartPosition.z);
	}

	public void SwitchStance()
	{
		IsSoldierInDefenseMode = !IsSoldierInDefenseMode;
		renderer.material.mainTexture = IsSoldierInDefenseMode ? SoldierDefenseImage : _DefaultImage;
	}

	public void SwitchReadyPosition()
	{
		IsCannonReady = !IsCannonReady;
		transform.Rotate (Vector3.up, 180f);
	}
	void OnSelected(GameObject sender)
	{
		if (OnTokenSelected != null)
			OnTokenSelected(gameObject);
	}

	void OnAttacked(GameObject sender)
	{
		if (OnTokenAttacked != null)
			OnTokenAttacked (gameObject);
	}

	void OnTriggered(GameObject sender)
	{
		if (OnAbilityTriggered != null) 
			OnAbilityTriggered (gameObject);
	}
}
